package com.alex.distributedlockredis.redissonlock;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

@Service
public class RedissonLockServiceAlex008 {
    private final RedissonClient redissonClient;

    public RedissonLockServiceAlex008(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    public void seckillWithRedisson() {
        // 获取锁对象
        RLock lock = redissonClient.getLock("seckill:lock");
        
        try {
            // 尝试加锁，最多等待100秒，上锁后10秒自动解锁
            boolean locked = lock.tryLock(100, 10, TimeUnit.SECONDS);
            if (locked) {
                // 执行业务逻辑
                System.out.println("获取锁成功，执行业务逻辑");
                Thread.sleep(2000); // 模拟业务执行
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            // 释放锁
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
}